﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using DTO;
using BLL;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Base;
using System.Collections;

namespace CRM.GUI.QLKhachHang
{
    public partial class ucAutomatic : UserControl
    {
        private List<DTO.RegionEntity> loadMien;
        private List<DTO.RegionEntity> loadTinhThanh;
        private List<CallAgentEntity> listCA;
        private List<vw_DWorking> tasklist;
        private List<CustomerEntity> listCustomerForDivide;

        public ucAutomatic()
        {
            InitializeComponent();
            IntialLoad();
        }
        private void IntialLoad()
        {
            grdDivAu.BestFitColumns();
            grdDivAu.OptionsView.ColumnAutoWidth = true;
            grdDivAu.ScrollStyle = ScrollStyleFlags.LiveHorzScroll | ScrollStyleFlags.LiveVertScroll;
            grdDivAu.HorzScrollVisibility = ScrollVisibility.Always;
            this.loadMien = SharedData.RegionList.Where(a => a.RegionLevel == 1).ToList();
            this.loadTinhThanh = SharedData.RegionList.Where(a => a.RegionLevel == 2).ToList();
            cmbColRegion.View.Columns.AddField("RegionName").Visible = true;
            cmbColRegion.DataSource = SharedData.RegionList.Where(a => a.RegionLevel == 1).ToList();
            cmbColRegion.DisplayMember = "RegionName";
            cmbColRegion.ValueMember = "Region_Code";
        }
        
        
        private void btnPK_Click(object sender, EventArgs e)
        {
            var listThaiKiAu = cmbThaiKiAu.EditValue.ToString().Split(',');
            var listCallType = cmbCallType.EditValue.ToString().Split(',');
            LoadCAFunc func = new LoadCAFunc();
            if (listCA.Where(a => a.Selected == true).Count() > 0)
            {
                bool errCode = false;
                int total = -1;

                if (rbtnDivideAll.Checked)
                {
                    //full
                    total = listCustomerForDivide.Count();
                }
                else
                {
                    //spec
                    if (txtNumberOfCall.Text.Trim() != "")
                    {
                        if (int.TryParse(txtNumberOfCall.Text.Trim(), out total))
                        {
                            if (total <= 0)
                            {
                                total = -1;
                                MessageBox.Show("Số lượng phân chia phải lớn hơn 0!");
                                return;
                            }
                            if (total > listCustomerForDivide.Count())
                            {
                                total = -1;
                                MessageBox.Show("Số lượng phân chia lớn hơn số lượng khách hàng hiện tại!");
                                return;
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("Không bỏ trống số lượng!");
                        return;
                    }
                }

                errCode = func.divideCustomerToCA(listCustomerForDivide, listCA, listThaiKiAu, listCallType, total);

                if (errCode)
                {
                    MessageBox.Show("Chia thành công!");
                    RefreshListCustomer();
                }
                else
                {
                    MessageBox.Show("Chia không thành công!");
                }
            }
            else
            {
                MessageBox.Show("Chưa chọn Call Agent!");
            }
        }

        private void cmbThaiKiAu_EditValueChanged(object sender, EventArgs e)
        {
            if (cmbThaiKiAu.Properties.DataSource == null)
            {
                cmbThaiKiAu.Text = "Thai kì";
            }

            EnablebuttonOK();
        }

        private void cmbCallType_EditValueChanged(object sender, EventArgs e)
        {
            //Show EDDS in combobox
            
            if (listCustomerForDivide != null)
            {
                if (!string.IsNullOrEmpty(cmbCallType.EditValue.ToString()))
                {
                    var listCallType = cmbCallType.EditValue.ToString().Split(',');
                    ArrayList listEDDS = new ArrayList();
                    foreach (var item in listCallType)
                    {
                        var listtmp = (from list in listCustomerForDivide.Where(a => a.CallStatus == int.Parse(item))
                                       group list by list.EDDS into g
                                       select new
                                       {
                                           EDDS = g.FirstOrDefault().EDDS,
                                           Count = g.Count(),
                                       });
                        foreach (var edds in listtmp)
                        {
                            listEDDS.Add(edds);
                        }
                    }
                    cmbThaiKiAu.Properties.DataSource = listEDDS.ToArray().Distinct();
                    cmbThaiKiAu.Properties.DisplayMember = "EDDS";
                    cmbThaiKiAu.Properties.ValueMember = "EDDS";
                    cmbThaiKiAu.CheckAll();

                    grdEDDS.DataSource = listEDDS.ToArray().Distinct().ToList();
                    
                }
                else
                {
                    cmbThaiKiAu.SetEditValue(null);
                    cmbThaiKiAu.Properties.DataSource = null;
                    grdEDDS.DataSource = null;
                }
            }

            EnablebuttonOK();
        }       


        private void cmbCollector_EditValueChanged(object sender, EventArgs e)
        {   
            //refresh
            RefreshListCustomer();
        } 

        private void dtpEndDate_ValueChanged(object sender, EventArgs e)
        {
            LoadSource();
        }

        private void dtpStartDate_ValueChanged(object sender, EventArgs e)
        {
            LoadSource();
        }

        private void LoadSource()
        {
            cmbSource.Properties.DataSource = null;
            LoadSourceFunc func = new LoadSourceFunc();
            cmbSource.Properties.DisplayMember = "SourceName";
            cmbSource.Properties.ValueMember = "Source_ID";
            cmbSource.Properties.DataSource = func.LoadSourceForDivide(dtpStartDate.Value, dtpEndDate.Value);
        }

        private void cmbSource_SelectionChangeCommitted(object sender, EventArgs e)
        {
            if (IsSourceHasValue())
            {
                RefreshUIForDivide();
            }
            else
            {
                MessageBox.Show("Chưa chọn Source");
            }
        }

        private bool IsSourceHasValue()
        { 
            int sourceid;
            if (int.TryParse(cmbSource.EditValue.ToString(), out sourceid) || sourceid > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private void RefreshUIForDivide()
        {
            LoadCAFunc func = new LoadCAFunc();
            LoadSource();
            if (IsSourceHasValue())
            {
                cmbCollector.Properties.DataSource = null;
                listCA = func.LoadTotalCallByAllCA();
                grdlDivAuto.DataSource = listCA;
                tasklist = func.CountDWList((int)cmbSource.EditValue);
                cmbCollector.Properties.DataSource = tasklist;
                cmbCollector.Properties.DisplayMember = "Collector_Code";
                cmbCollector.Properties.ValueMember = "Collector_ID";                
            }
        }

        private void rbtnDivideAll_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtnDivideAll.Checked)
            {
                txtNumberOfCall.Enabled = false;
            }
            else
            {
                txtNumberOfCall.Enabled = true;
            }
        }

        private void EnablebuttonOK()
        {
            if (cmbCallType.EditValue != null)
            {
                if (!string.IsNullOrEmpty(cmbCallType.EditValue.ToString()))
                {
                    if (cmbThaiKiAu.EditValue != null)
                    {
                        if (!string.IsNullOrEmpty(cmbThaiKiAu.EditValue.ToString()))
                        {
                            btnPK.Enabled = true;
                        }
                        else
                        {
                            btnPK.Enabled = false;
                        }
                    }
                    else
                    {
                        btnPK.Enabled = false;
                    }
                }
                else
                {
                    btnPK.Enabled = false;
                }
            }
            else
            {
                btnPK.Enabled = false;
            }
        }

        private void RefreshListCustomer()
        {
            cmbCallType.Properties.Items.Clear();
            cmbThaiKiAu.Properties.Items.Clear();
            grdlDivAuto.DataSource = null;
            if (cmbSource.EditValue != null && cmbCollector.EditValue != null)
            {

                LoadCAFunc func = new LoadCAFunc();
                listCustomerForDivide = func.LoadCustomerForDivide((int)cmbSource.EditValue, (int)cmbCollector.EditValue);

                //Show CallStatus in Combobox
                cmbCallType.Properties.DataSource = from a in listCustomerForDivide.Where(a => a.Collector_ID == (int)cmbCollector.EditValue)
                                                    group a by a.CallStatus into g
                                                    select new
                                                    {
                                                        CallStatus = g.FirstOrDefault().CallStatus,
                                                        CallStatusName = SharedData.CallStatusList.Where(a => a.CallStatus_ID == g.FirstOrDefault().CallStatus).SingleOrDefault().CallStatusName,
                                                    };
                cmbCallType.Properties.DisplayMember = "CallStatusName";
                cmbCallType.Properties.ValueMember = "CallStatus";
                cmbCallType.CheckAll();
                //Refresh UI
                RefreshUIForDivide();

            }
        }

    }
}


